package org.dbstar.scheduler.control.db.conf;

import java.sql.Types;
import java.util.List;

import net.sf.json.JSONSerializer;

import org.dbstar.scheduler.beans.JobConf;
import org.dbstar.scheduler.beans.ParameterDefine;
import org.dbstar.scheduler.identifier.Identifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;


/**
 * 快速插入JobConf对象
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-4-24
 */
public class JobConfInsert extends SimpleJdbcInsert {
	public JobConfInsert(JdbcTemplate jdbcTemplate) {
		super(jdbcTemplate);
		withTableName("SCHD_JOB_CONF");
		usingColumns("SYSTEM_IDENTIFIER", "SEQUENCE", "IDENTIFIER", "CATALOG", "TYPE", "NAME", "DESCRIPTION",
				"RESOURCE", "CONTENT", "PARAMETER_SIZE", "PARAMETER_DATA", "MAX_RETRY", "CREATE_TIME", "OWNER");
	}

	public int insertJobConf(JobConf conf, Identifier identifier) {
		MapSqlParameterSource source = new MapSqlParameterSource();
		source.addValue("SYSTEM_IDENTIFIER", identifier.getSystemIdentifier(), Types.VARCHAR);
		source.addValue("SEQUENCE", identifier.getSequence(), Types.INTEGER);
		source.addValue("IDENTIFIER", identifier.getStringIdentifier(), Types.VARCHAR);
		source.addValue("CATALOG", conf.getCatalog(), Types.INTEGER);
		source.addValue("TYPE", conf.getType(), Types.VARCHAR);
		source.addValue("NAME", conf.getName(), Types.VARCHAR);
		source.addValue("DESCRIPTION", conf.getDescription(), Types.VARCHAR);
		source.addValue("RESOURCE", conf.getResource(), Types.VARCHAR);
		source.addValue("CONTENT", conf.getContent(), Types.VARCHAR);
		source.addValue("PARAMETER_SIZE", conf.getParameterSize(), Types.INTEGER);
		source.addValue("PARAMETER_DATA", parseParametersJson(conf.getParameters()), Types.VARCHAR);
		source.addValue("MAX_RETRY", conf.getMaxRetry(), Types.INTEGER);
		source.addValue("CREATE_TIME", conf.getCreateTime(), Types.BIGINT);
		source.addValue("OWNER", conf.getOwner(), Types.VARCHAR);
		return super.execute(source);
	}

	private String parseParametersJson(List<ParameterDefine> parameters) {
		if (parameters == null || parameters.isEmpty()) {
			return null;
		} else {
			return JSONSerializer.toJSON(parameters, new ParameterDefineJsonConfig()).toString();
		}
	}
}
